import React, { useState } from 'react'
import { useQuery } from 'remax'
import { Image, Text, View, switchTab } from 'remax/one'
import { usePageEvent } from 'remax/macro'
import {
  Swiper,
  SwiperItem,
  makePhoneCall,
  openLocation,
  previewImage,
  requestPayment,
  stopPullDownRefresh,
  showModal,
} from 'remax/wechat'
import { Button, Icon, Row, Space, Tag } from 'annar'
import dayjs from 'dayjs'
import useCloud, { mutateCloud, requestCloud } from '@/hooks/use-cloud'
import useLocation from '@/hooks/use-location'
import useUser from '@/hooks/use-user'
import Login from '@/components/login'
import styles from './index.css'

export default () => {
  const { data: uData, mutate: uMutate } = useUser()
  const [loginPopup, setLoginPopup] = useState(false)

  const { _id, q } = useQuery()
  let arr
  if (q) {
    arr = decodeURIComponent(q).match(
      /\/customer\/promotion\/(.*)\/screen\/(.*)$/
    )
  }
  const pId = arr && arr[1] ? arr[1] : _id
  const { location } = useLocation()
  const { data, mutate } = useCloud(
    location && pId ? 'list-promotion-cast' : null,
    {
      _id: pId,
      location,
    }
  )

  usePageEvent('onPullDownRefresh', async () => {
    await mutate()
    stopPullDownRefresh()
  })

  usePageEvent('onShareAppMessage', async () => {
    return { title: '蜗大郎 - ' + item.promotion.name }
  })

  if (!location) {
    return null
  }
  if (data === undefined) {
    return null
  } else if (!data || !data[0]) {
    return <View className="empty-view small-text">此活动不存在或已过期</View>
  }
  const item = data[0]

  const {
    promotion: {
      name,
      description,
      imgUrls,
      price,
      originalPrice,
      quota,
      store,
    },
    currQuota,
  }: WBG.PromotionCast = item
  const currDate = dayjs().format('YYYY-MM-DD')

  const pay = async () => {
    try {
      const { orderId, payment } = await requestCloud('pay', {
        $url: 'add-order',
        promotionCastId: pId,
      })
      await requestPayment(payment)
      await requestCloud('pay', {
        $url: 'update-order',
        _id: orderId,
      })
      mutateCloud('list-order')
      mutateCloud('get-user')
      switchTab({ url: '/pages/order-list/index' })
    } catch ({ errMsg }) {
      let content
      if (/exceed quota/.test(errMsg)) {
        content = '今日已售完，请明日购买'
      } else if (/unified order failed/.test(errMsg)) {
        content = '下单失败，请稍后重试'
      } else if (/requestPayment:fail cancel/.test(errMsg)) {
        content = '支付已取消，可在“我的订单”中重新支付'
      } else if (/trade failed/.test(errMsg)) {
        content = '交易状态有误，请重试'
      } else {
        content = '网络错误'
      }
      showModal({
        title: '支付失败',
        content,
        showCancel: false,
        confirmText: '我知道了',
      })
    }
  }

  return (
    <>
      <Login
        open={loginPopup}
        onClose={() => {
          setLoginPopup(false)
        }}
        onLogin={() => {
          pay()
        }}
      />
      <View className={styles.mainArea}>
        <Space className={styles.mainBox} direction="vertical" size={20}>
          <View className="xlarge-text ellipsis">{name}</View>
          <Space size={12}>
            <Tag className="no-border" color="yellow">
              好评率：100%
            </Tag>
            <Tag className="no-border" color="green">
              去过的同学人数：0人
            </Tag>
          </Space>
          <Swiper
            className={styles.swiper}
            indicatorDots={imgUrls.length > 1}
            autoplay
            circular
          >
            {imgUrls.map((v, i) => (
              <SwiperItem key={i}>
                <Image
                  className={styles.swiperImg}
                  src={v}
                  mode="aspectFill"
                  onTap={() => {
                    previewImage({ urls: imgUrls, current: v })
                  }}
                />
              </SwiperItem>
            ))}
          </Swiper>
          <Space align="center" size={12}>
            <Text className="large-text alarm-text">￥{price}</Text>
            <Text className="deleted-text">￥{originalPrice}</Text>
            <Tag className="no-border" color="red">
              {Math.round((price / originalPrice) * 100) / 10} 折
            </Tag>
          </Space>
          <Row className={styles.storeBox} align="middle">
            <View>
              <Image
                className={styles.avatarImg}
                src={store.imgUrl}
                mode="aspectFill"
              />
            </View>
            <Space
              className={styles.storeBoxRight}
              direction="vertical"
              size={12}
            >
              <Row justify="space-between" align="middle">
                <View className="large-text ellipsis">{store.name}</View>
                <View
                  onTap={() => {
                    makePhoneCall({ phoneNumber: store.phoneNumber })
                  }}
                >
                  <Icon type="phone" size="40px" color="#666" />
                </View>
              </Row>
              <Tag className="no-border" color="yellow">
                {store.description}
              </Tag>
              <View
                hoverClassName="hover"
                onTap={() => {
                  openLocation({
                    longitude: store.location.coordinates[0],
                    latitude: store.location.coordinates[1],
                  })
                }}
              >
                <Row justify="space-between" align="middle">
                  <Row>
                    <Icon type="location" size="40px" color="#666" />
                    <View>
                      <View className="small-text">{store.address}</View>
                      <View className="small-text">
                        距离您 {Math.round((store.distance / 1000) * 10) / 10}{' '}
                        公里
                      </View>
                    </View>
                  </Row>
                  <Icon type="right" size="30px" color="#666" />
                </Row>
              </View>
            </Space>
          </Row>
        </Space>
        <View className={styles.mainBox}>{description}</View>
      </View>
      <Row className={styles.bottomArea} justify="end" align="middle">
        <Text className="small-text">
          今日剩余{' '}
          <Text style={{ color: '#ff4f00' }}>
            {currQuota[currDate] || 0}/{quota}
          </Text>
        </Text>
        <Button
          className={styles.bottomButton}
          look="orange"
          disabled={!currQuota[currDate] || currQuota[currDate] <= 0}
          onTap={() => {
            if (!uData) {
              setLoginPopup(true)
              return
            } else {
              pay()
            }
          }}
        >
          {currQuota[currDate] && currQuota[currDate] > 0
            ? '立即抢购'
            : '今日已告罄'}
        </Button>
      </Row>
    </>
  )
}
